from django.shortcuts import render,get_object_or_404

# Create your views here.

from django.http import HttpResponse

from .models import Category,Post,Tag

import markdown

# 引入正则
import re

# version_6 处理锚点
from django.utils.text import slugify
from markdown.extensions.toc import TocExtension

# 第一版view，HttpResponse封装字符串
#def index(request):
#    return HttpResponse("Hello,world.You're at the polls index")


# 第二版view，引入模板HTML

#def index(request):
#    n = Category.objects.get().name
#    return render(request,'polls/index.html',context = {'title':'我的博客首页','welcome':'欢迎访问我的博客首页','name':n})


# 第三版view,引入静态文件static

# 第四版，引入Markdown

def index(request):
    post_list = Post.objects.all().order_by('-created_time')
    return render(request,'polls/index.html',context={'post_list':post_list})


# add detail函数

# def detail(request,pk):
#    post = get_object_or_404(Post,pk=pk)
#    return render(request,'polls/detail.html',context={'post':post})

# 加入markdown

#def detail(request, pk):
#    post = get_object_or_404(Post, pk=pk)
#    post.body = markdown.markdown(post.body,
#                                  extensions=[
#                                      'markdown.extensions.extra',
#                                      'markdown.extensions.codehilite',
#                                      'markdown.extensions.toc',
#                                  ])
#    return render(request, 'polls/detail.html', context={'post': post})

# version5 在页面的任何地方插入目录

def detail(request,pk):
    post = get_object_or_404(Post,pk=pk)

    # 阅读量+1，引用的是post这个对象的方法,post是Post实例化的，Post的方法post也可以使用
    post.increase_views()

    md = markdown.Markdown(extensions=[
        'markdown.extensions.extra',
        'markdown.extensions.codehilite',
        # version_6 注释toc,加入TocExtension
        #'markdown.extensions.toc',
        TocExtension(slugify=slugify),
        ]
    )


    post.body = md.convert(post.body)
    post.toc = md.toc


    # 处理没有目录的文章
    m = re.search(r'<div class="toc">\s*<ul>(.*)</ul>\s*</div>',md.toc,re.S)
    post.toc = m.group(1) if m is not None else ''
    return render(request,'polls/detail.html',context={'post':post})


#  version_8  新增归档页面
def archive(request,year,month):
    post_list = Post.objects.filter(created_time__year=year,created_time__month=month).order_by('-created_time')

    return render(request,'polls/index.html',context={'post_list':post_list})


# version_8 新增类别
def category(request,pk):
    # 记得import category
    cate = get_object_or_404(Category,pk=pk)
    post_list = Post.objects.filter(category=cate).order_by('created_time')
    return render(request,'polls/index.html',context={'post_list':post_list})


# version_8 新增标签页
def tag(request,pk):
    t = get_object_or_404(Tag,pk=pk)
    post_list = Post.objects.filter(tags=t).order_by('-created_time')
    return render(request,'polls/index.html',context={'post_list':post_list})
